<template>
  <div>
    <van-cell
      v-for="(item, index) in hightLightSuggestions"
      :key="index"
      icon="search"
      @click="$emit('update-keywords', suggestions[index])"
    >
      <template #title>
        <span v-html="item"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSuggestionsAPI } from '@/api'
export default {
  data() {
    return {
      suggestions: []
    }
  },
  computed: {
    hightLightSuggestions() {
      const reg = new RegExp(this.keyword, 'ig')
      return this.suggestions.map((str) => {
        // item" Angular
        return str.replace(
          reg,
          (match) => `<span style="color:red">${match}</span>`
        )
      })
    }
  },
  props: {
    keyword: {
      type: String,
      required: true
    }
  },
  watch: {
    // 监视属性
    // 字符串的写法（也可以在 handler）
    // 在 methods身上找方法
    keyword: {
      handler: 'getSearchSuggestions',
      immediate: true
    }
  },
  methods: {
    // console.log(data);
    // 版本一 数组里面的null 全去掉
    // this.suggestions = data.data.options.filter((item) => item !== null)
    // 版本二
    // this.suggestions = data.data.options.filter((item) => Boolean(item))

    // 版本三
    // 防抖 在间隔一段时间内只执行一次
    getSearchSuggestions: debounce(async function () {
      const { data } = await getSuggestionsAPI(this.keyword)
      this.suggestions = data.data.options.filter(Boolean)
    }, 300)
  }
}
</script>

<style></style>
